/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import processor.SqlFormat;
import processor.SqlGrammar;
import processor.TemplateStatement;

/**
 *
 * @author DYNG09
 */
public class EditTab extends JPanel {

    private TemplateStatement template;
    private JTextArea editArea;
    private String nameTab;
    private Socket s;
    private ViewResultPanel vR;

    public EditTab(String tabTitle, Socket s) {
        this.setLayout(new BorderLayout());

        template = new TemplateStatement();
        nameTab = tabTitle;
        this.s = s;

        initGUI();
    }

    /**
     * initialize GUI for edit panel
     */
    private void initGUI() {
        editArea = new JTextArea();
        editArea.setFont(new Font("Monospaced", 1, 14));
        editArea.setWrapStyleWord(true);
        editArea.setSelectionColor(Color.GREEN);
        editArea.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                editArea.getHighlighter().removeAllHighlights();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                editArea.getHighlighter().removeAllHighlights();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                editArea.getHighlighter().removeAllHighlights();
            }
        });

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        JButton btnExec = new JButton("View result");
        btnExec.setIcon(new ImageIcon(getClass().getResource("/resources/ViewResult.png")));
        btnExec.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Execute this sql statement");
                doExecute();
            }
        });
        JLabel tfUsingTemplate = new JLabel("                           Using template statement:    ");

        JComboBox cboTemplate = new JComboBox();
        setList(cboTemplate, template.getLstNameTemplate());
        cboTemplate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ("comboBoxChanged".equals(command)) {
                    JComboBox cbo = (JComboBox) e.getSource();
                    int index = cbo.getSelectedIndex();
                    fillTemplate(getEditArea(), index);
                }
            }
        });
        JButton btnClearAll = new JButton("Clear All");
        btnClearAll.setIcon(new ImageIcon(getClass().getResource("/resources/ClearAll.png")));
        btnClearAll.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                clearAllText();
            }
        });

        bottomPanel.add(btnExec);
        bottomPanel.add(tfUsingTemplate);
        bottomPanel.add(cboTemplate);
        bottomPanel.add(btnClearAll);

        JPanel betweenPanel = new JPanel();
        betweenPanel.setLayout(new BoxLayout(betweenPanel, BoxLayout.LINE_AXIS));
        JScrollPane sp = new JScrollPane();
        getEditArea().setRows(20);
        getEditArea().setColumns(90);
        sp.setBorder(BorderFactory.createEtchedBorder());
        sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        sp.setViewportView(getEditArea());
        betweenPanel.add(sp);
        vR = new ViewResultPanel();
        betweenPanel.add(vR);

        this.add(betweenPanel, BorderLayout.CENTER);
        this.add(bottomPanel, BorderLayout.SOUTH);
    }

    /**
     * Execute selected queries
     */
    private void doExecute() {
        String text = editArea.getText();
        String selectedText = null;
        if ((selectedText = editArea.getSelectedText()) == null) {
            JOptionPane.showMessageDialog(null, "You must select some line of expression!");
        } else {
            int startPos = 0;
            for (int i = 0; i < text.length() - selectedText.length() - 1; i++) {
                if (text.substring(i, i + selectedText.length()).equals(selectedText)) {
                    startPos = i;
                    break;
                }
            }
            //check correction
            SqlGrammar gr = new SqlGrammar(selectedText, editArea.getHighlighter(), startPos);
            boolean r = gr.check();
            if (r) {
                //format query
                SqlFormat format = new SqlFormat(this.editArea.getSelectedText());
                this.editArea.setText(format.format());
                //parse to xml, send document and receive result
                LoadingDialog ld = new LoadingDialog(this, this.editArea.getText(), s);
                ld.run();
                //view reult
                JTable t = ld.getTableResult();
                if (t != null) {
                    this.vR.setTableResult(t);
                    this.vR.setResult();
                }
            }
        }
    }

    /**
     * set a list into combo box
     *
     * @param cbo
     * @param list
     */
    private void setList(JComboBox cbo, ArrayList<String> list) {
        for (int i = 0; i < list.size(); i++) {
            cbo.addItem(list.get(i));
        }
    }

    /**
     * fill text template into edit area
     *
     * @param editArea
     * @param index
     */
    private void fillTemplate(JTextArea editArea, int index) {
        if (index > 0) {
            editArea.setText(editArea.getText() + template.getLstTemplate().get(index));
        }
    }

    /**
     * clear all text in edit area
     */
    private void clearAllText() {
        getEditArea().setText("");
    }

    /**
     * @return the editArea
     */
    public JTextArea getEditArea() {
        return editArea;
    }

    /**
     * @param editArea the editArea to set
     */
    public void setEditArea(JTextArea editArea) {
        this.editArea = editArea;
    }

    /**
     * @return the nameTab
     */
    public String getNameTab() {
        return nameTab;
    }

    /**
     * @param nameTab the nameTab to set
     */
    public void setNameTab(String nameTab) {
        this.nameTab = nameTab;
    }
}
